package cn.wolfcode.shiro.realm;

import cn.wolfcode.shiro.dao.IPermissionDAO;
import cn.wolfcode.shiro.dao.IRoleDAO;
import cn.wolfcode.shiro.dao.IUserDAO;
import cn.wolfcode.shiro.domain.User;
import lombok.Setter;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import java.util.ArrayList;
import java.util.List;


/**
 * @author longhai
 * @date 2018/12/13 - 18:06
 */
public class UserRealm  extends AuthorizingRealm {

    @Setter
    public IUserDAO userDao;

    @Setter
    public IPermissionDAO permissionDAO;

    @Setter
    public IRoleDAO roleDAO;

    @Override
    public String getName() {
        return "UserRealm";
    }

    //授权操作
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
      User user=(User) principalCollection.getPrimaryPrincipal();

        List<String> permissions=new ArrayList<String>();
        List<String> roles =new ArrayList<String>();
        if ("admin".equals(user.getUsername())){


           roles= roleDAO.getAllRoleSn();
        }
        else {
           roles= roleDAO.getRoleSnByUserId(user.getId());
            permissions=permissionDAO.getPermissionResourceByUserId(user.getId());


        }
        SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
        info.addStringPermissions(permissions);
        info.addRoles(roles);
        return info;
    }

    //认证操作
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //从token中获取登录的用户名， 查询数据库返回用户信息
        String username = (String) authenticationToken.getPrincipal();
        User user = userDao.getUserByUsername(username);

        if(user == null){
            return null;
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, user.getPassword(),
                ByteSource.Util.bytes(user.getUsername()),
                getName());
        return info;
    }


    //当执行注销的时候（/loginOut）清除缓存
    @Override
    protected void clearCache(PrincipalCollection principals) {
        //获取当前等的用户凭证，然后清除
         principals = SecurityUtils.getSubject().getPrincipals();
        super.clearCache(principals);
    }
}
